import type { Request, Response } from 'express';
import { parse } from 'url';
import type { TableEntList, TableEntListParams } from '@/services/common/ent/typings';

// mock tableListDataSource
const getList = () => {
  const dataSource: TableEntList[] = [];
  dataSource.push({
    tradeCode: '1100696075',
    tradeName: '北京世纪周峰商业设备有限公司',
    emsNo: 'L0100B19A004',
    emsClass: '6|物流账册'
  });
  dataSource.push({
    tradeCode: '1100696075',
    tradeName: '北京世纪周峰商业设备有限公司',
    emsNo: 'H010018A0453',
    emsClass: '2|H账册'
  });
  return dataSource;
};

function getEntInfoList(req: Request, res: Response, u: string) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }
  const { current = 1, pageSize = 10 } = req.query;
  const params = parse(realUrl, true).query as unknown as TableEntListParams;

  const tableListDataSource: TableEntList[] = getList();
  let dataSource = [...tableListDataSource].slice(
    ((current as number) - 1) * (pageSize as number),
    (current as number) * (pageSize as number),
  );
  if (params.sorter) {
    const sorter = JSON.parse(params.sorter as any);
    dataSource = dataSource.sort((prev, next) => {
      let sortNumber = 0;
      Object.keys(sorter).forEach((key) => {
        if (sorter[key] === 'descend') {
          if (prev[key] - next[key] > 0) {
            sortNumber += -1;
          } else {
            sortNumber += 1;
          }
          return;
        }
        if (prev[key] - next[key] > 0) {
          sortNumber += 1;
        } else {
          sortNumber += -1;
        }
      });
      return sortNumber;
    });
  }
  if (params.filter) {
    const filter = JSON.parse(params.filter as any) as Record<string, string[]>;
    if (Object.keys(filter).length > 0) {
      dataSource = dataSource.filter((item) => {
        return Object.keys(filter).some((key) => {
          if (!filter[key]) {
            return true;
          }
          if (filter[key].includes(`${item[key]}`)) {
            return true;
          }
          return false;
        });
      });
    }
  }

  if (params.tradeCode) {
    dataSource = dataSource.filter((data) => data.tradeCode?.includes(params.tradeCode || ''));
  }

  let finalPageSize = 10;
  if (params.pageSize) {
    finalPageSize = parseInt(`${params.pageSize}`, 10);
  }

  const result = {
    data: dataSource,
    total: tableListDataSource.length,
    success: true,
    pageSize: finalPageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };

  return res.json(result);
}

export default {
  'GET /api/entInfoList': getEntInfoList,
};
